<template>
  <div class="min-h-screen bg-gray-50">
    <NavBar />

    <div class="max-w-4xl mx-auto px-4 py-10 space-y-6">
      <section v-if="!isLoggedIn" class="bg-white rounded-2xl shadow p-8 text-center space-y-4">
        <h1 class="text-3xl font-bold text-gray-900">VIP 会员中心</h1>
        <p class="text-gray-600 text-lg">
          登录后即可开通会员，解锁全部 VIP 章节与专属特权。
        </p>
        <button
          class="px-6 py-3 bg-orange-500 text-white rounded-xl hover:bg-orange-600 transition-colors"
          @click="$router.push('/login')"
        >
          立即登录
        </button>
      </section>

      <template v-else>
        <section class="bg-white rounded-2xl shadow p-6 space-y-4">
          <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
            <div>
              <p class="text-sm uppercase tracking-wide text-gray-500">当前状态</p>
              <h1 class="text-3xl font-bold text-gray-900 mt-1">VIP 会员中心</h1>
              <p class="text-gray-600 mt-2">畅享完整阅读体验、抢先更新等专属权益。</p>
            </div>
            <div class="text-right">
              <p class="text-sm text-gray-500">当前账号</p>
              <p class="text-lg font-semibold text-gray-900">
                {{ userInfo?.nickname || '用户' }}
              </p>
              <p class="text-sm mt-1">
                状态：
                <span :class="isVip ? 'text-emerald-600 font-semibold' : 'text-gray-700'">
                  {{ isVip ? '已开通 VIP' : '普通用户' }}
                </span>
              </p>
              <p v-if="vipExpireTime" class="text-sm text-gray-500">有效期至：{{ vipExpireTime }}</p>
            </div>
          </div>

          <div class="rounded-xl bg-orange-50 border border-orange-100 px-4 py-3 text-sm text-orange-700 leading-relaxed">
            <p>· 当前为支付宝沙箱环境，支付金额为 0.01 元，仅用于测试。</p>
            <p>· 支付成功后请点击“刷新会员状态”，或输入订单号查询订单。</p>
            <p>· 若支付页面被浏览器拦截，请允许弹出窗口后重新发起支付。</p>
          </div>

          <div class="flex gap-3">
            <button
              class="px-4 py-2 rounded-xl border border-gray-200 text-gray-700 hover:bg-gray-50 transition-colors"
              :disabled="refreshing"
              @click="handleRefreshProfile"
            >
              {{ refreshing ? '刷新中…' : '刷新会员状态' }}
            </button>
            <button
              class="px-4 py-2 rounded-xl border border-gray-200 text-gray-700 hover:bg-gray-50 transition-colors"
              @click="$router.push('/novels')"
            >
              返回书库
            </button>
          </div>

          <div v-if="successMessage" class="rounded-xl border border-emerald-200 bg-emerald-50 text-emerald-700 px-4 py-3">
            {{ successMessage }}
          </div>
          <div v-if="errorMessage" class="rounded-xl border border-red-200 bg-red-50 text-red-700 px-4 py-3">
            {{ errorMessage }}
          </div>
        </section>

        <section class="bg-white rounded-2xl shadow p-6 space-y-6">
          <div>
            <h2 class="text-xl font-semibold text-gray-900">选择会员套餐</h2>
            <p class="text-sm text-gray-500">沙箱测试环境仅提供 0.01 元体验套餐。</p>
          </div>

          <div class="grid gap-4 sm:grid-cols-2">
            <article class="relative rounded-2xl border border-orange-500 shadow-lg ring-2 ring-orange-100 p-6 space-y-3">
              <div class="absolute top-4 right-4">
                <span class="px-3 py-1 rounded-full bg-orange-100 text-orange-600 text-xs font-semibold">
                  沙箱价
                </span>
              </div>
              <h3 class="text-lg font-semibold text-gray-900">VIP 体验套餐</h3>
              <p class="text-3xl font-bold text-gray-900">
                ¥0.01
                <span class="text-sm text-gray-500 ml-1">/ 次</span>
              </p>
              <p class="text-sm text-gray-600">沙箱环境调试专用。</p>
              <ul class="space-y-2 text-sm text-gray-600">
                <li class="flex items-center gap-2"><span class="text-emerald-500">✔</span><span>解锁所有 VIP 章节</span></li>
                <li class="flex items-center gap-2"><span class="text-emerald-500">✔</span><span>优先获取最新更新</span></li>
                <li class="flex items-center gap-2"><span class="text-emerald-500">✔</span><span>计划内的更多权益示例</span></li>
              </ul>
            </article>
          </div>

          <div class="flex flex-col sm:flex-row sm:items-center gap-3">
            <button
              class="px-6 py-3 rounded-xl bg-orange-500 text-white text-lg font-semibold hover:bg-orange-600 transition-colors disabled:opacity-60"
              :disabled="payLoading"
              @click="handlePay"
            >
              {{ payLoading ? '正在打开支付页…' : '立即开通（¥0.01）' }}
            </button>
            <p class="text-sm text-gray-500">支付将在新窗口打开，请确认浏览器允许弹出窗口。</p>
          </div>
        </section>

        <section class="bg-white rounded-2xl shadow p-6 space-y-4">
          <h2 class="text-xl font-semibold text-gray-900">订单查询</h2>
          <p class="text-sm text-gray-500">输入订单编号即可查看当前记录的支付状态。</p>

          <div class="flex flex-col md:flex-row gap-3">
            <input
              v-model="orderNo"
              type="text"
              placeholder="请输入订单号，如：TEST_ABCDEF1234"
              class="flex-1 px-4 py-2.5 border border-gray-200 rounded-xl focus:ring-2 focus:ring-orange-400 focus:border-transparent transition-shadow"
            />
            <button
              class="px-5 py-2.5 rounded-xl bg-gray-900 text-white hover:bg-gray-800 transition-colors disabled:opacity-60"
              :disabled="!orderNoTrimmed || checking"
              @click="handleCheckOrder"
            >
              {{ checking ? '查询中…' : '查询订单' }}
            </button>
          </div>

          <div v-if="orderError" class="rounded-xl border border-red-200 bg-red-50 text-red-700 px-4 py-3">
            {{ orderError }}
          </div>

          <div v-if="orderInfo" class="rounded-xl border border-gray-200 bg-gray-50 px-4 py-3 space-y-2 text-sm text-gray-700">
            <div class="flex justify-between items-center">
              <p><span class="font-semibold text-gray-900">订单号：</span>{{ orderInfo.out_trade_no }}</p>
              <span :class="orderInfo.status === 'PAID' ? 'text-emerald-600 font-semibold' : 'text-gray-700'">
                {{ orderInfo.status === 'PAID' ? '已支付' : '未支付' }}
              </span>
            </div>
            <p><span class="font-semibold text-gray-900">金额：</span>{{ orderInfo.total_amount }} 元</p>
            <p><span class="font-semibold text-gray-900">创建时间：</span>{{ formatDateTime(orderInfo.create_time) }}</p>
            <p v-if="orderInfo.pay_time">
              <span class="font-semibold text-gray-900">支付时间：</span>{{ formatDateTime(orderInfo.pay_time) }}
            </p>
            <div class="flex flex-wrap gap-3 pt-2">
              <button
                v-if="orderInfo.status !== 'PAID'"
                class="px-3 py-2 rounded-lg border border-gray-300 text-sm hover:bg-gray-100 transition-colors"
                @click="handleCheckOrder"
              >
                刷新订单状态
              </button>
              <button
                class="px-3 py-2 rounded-lg border border-gray-300 text-sm hover:bg-gray-100 transition-colors"
                @click="openGatewayPage(orderInfo.out_trade_no)"
              >
                前往支付宝查询
              </button>
            </div>
          </div>
        </section>

        <section class="bg-white rounded-2xl shadow p-6 space-y-4">
          <h2 class="text-xl font-semibold text-gray-900">常见问题</h2>
          <dl class="space-y-4 text-sm text-gray-600">
            <div>
              <dt class="font-semibold text-gray-900">支付金额为什么是 0.01 元？</dt>
              <dd>当前处于支付宝沙箱环境，金额仅用于调试，真实环境可根据业务设置真实价格。</dd>
            </div>
            <div>
              <dt class="font-semibold text-gray-900">支付成功但状态未更新怎么办？</dt>
              <dd>稍等几秒后点击“刷新会员状态”或查询订单。若仍未更新，可再次调用支付宝网关查询。</dd>
            </div>
            <div>
              <dt class="font-semibold text-gray-900">弹窗被拦截怎么办？</dt>
              <dd>浏览器通常会提示弹窗被阻止，请允许当前站点弹出窗口后重新操作。</dd>
            </div>
          </dl>
        </section>
      </template>
    </div>
  </div>
</template>

<script setup>
import { computed, ref } from 'vue'
import { storeToRefs } from 'pinia'
import NavBar from '@/components/layout/NavBar.vue'
import { openVipPayment, fetchVipOrder, createGatewayQuery } from '@/api/vip'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()
const { isLoggedIn, userInfo } = storeToRefs(userStore)

const successMessage = ref('')
const errorMessage = ref('')
const payLoading = ref(false)
const refreshing = ref(false)

const orderNo = ref('')
const orderInfo = ref(null)
const orderError = ref('')
const checking = ref(false)

const isVip = computed(() => Number(userInfo.value?.vip_status) === 2)
const vipExpireTime = computed(() => {
  const expire = userInfo.value?.vip_expires_at
  if (!expire) return ''
  const date = new Date(expire)
  return Number.isNaN(date.getTime()) ? expire : date.toLocaleString()
})

const orderNoTrimmed = computed(() => orderNo.value.trim())

const handlePay = async () => {
  errorMessage.value = ''
  successMessage.value = ''
  payLoading.value = true
  try {
    const { fallbackToSelf } = await openVipPayment({
      amount: '0.01',
      subject: 'VIP 体验套餐',
      target: '_blank',
    })
    successMessage.value = fallbackToSelf
      ? '支付页面已在当前窗口打开，完成支付后返回此页并刷新会员状态。'
      : '支付页面已在新窗口打开，请完成支付后刷新会员状态。'
  } catch (error) {
    console.error('打开支付页面失败:', error)
    errorMessage.value = error?.message || '打开支付页面失败，请稍后再试。'
  } finally {
    payLoading.value = false
  }
}

const handleRefreshProfile = async () => {
  refreshing.value = true
  successMessage.value = ''
  errorMessage.value = ''
  try {
    await userStore.refreshUserInfo()
    successMessage.value = '会员信息已更新为最新状态。'
  } catch (error) {
    console.error('刷新会员信息失败:', error)
    errorMessage.value = error?.message || '刷新会员状态失败，请稍后再试。'
  } finally {
    refreshing.value = false
  }
}

const handleCheckOrder = async () => {
  orderError.value = ''
  orderInfo.value = null
  successMessage.value = ''
  checking.value = true
  try {
    const data = await fetchVipOrder(orderNoTrimmed.value)
    orderInfo.value = data
  } catch (error) {
    console.error('查询订单失败:', error)
    orderError.value = error?.message || '查询失败，请确认订单号是否正确。'
  } finally {
    checking.value = false
  }
}

const openGatewayPage = async (outTradeNo) => {
  try {
    const result = await createGatewayQuery(outTradeNo)
    const url = `${result.gateway}?${result.query}`
    window.open(url, '_blank', 'noopener=yes')
  } catch (error) {
    console.error('请求支付宝查询链接失败:', error)
    orderError.value = error?.message || '无法打开支付宝查询页面，请稍后再试。'
  }
}

const formatDateTime = (value) => {
  if (!value) return ''
  const date = new Date(value)
  return Number.isNaN(date.getTime()) ? value : date.toLocaleString()
}
</script>

<style scoped>
article::after {
  content: '';
}
</style>

